package jp.co.dailyReport.weeklyReport.sql;

import java.util.Vector;
import java.util.Calendar;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import org.apache.log4j.Logger;
import jp.co.dailyReport.Executer;
import jp.co.dailyReport.weeklyReport.WeeklyReport;
import jp.co.dailyReport.Utilities;

/**
 * 週報情報を取得するクラスです。
 */
public class WeeklyReportLoadForEditExecuter implements Executer {

	private static Logger log = Logger.getLogger(WeeklyReportLoadForEditExecuter.class);
	private Calendar workDateStart;
	private Calendar workDateEnd;
	private int projectId;

    public WeeklyReportLoadForEditExecuter(int projectId,Calendar workDateStart,Calendar workDateEnd) {
        this.workDateStart = workDateStart;
		this.workDateEnd = workDateEnd;
		this.projectId = projectId;
	}

	/**
	 * プロジェクトID・開始作業日・終了作業日を基に、週報情報を取得します。
	 * 
	 * @param conn コネクションオブジェクト
	 * @return 週報オブジェクトの配列
	 * @throws SQLException
	 */
    public Object[] execute(Connection conn) throws SQLException {

        ResultSet rset = null;
        PreparedStatement pstmt = null;
        String sql = "select * from weeklyReport where projectId=? and workDateStart=? and workDateEnd=?";
		log.debug("sql: " + sql);
        Vector answer = new Vector();
        try {
            pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, projectId);
			pstmt.setDate(2, new Date(workDateStart.getTime().getTime()));
			pstmt.setDate(3, new Date(workDateEnd.getTime().getTime()));
			rset = pstmt.executeQuery();
			WeeklyReport weeklyReport;
			while(rset.next()) {
				weeklyReport = new WeeklyReport();
				weeklyReport.setWeeklyReportId(rset.getInt("weeklyReportId"));
				weeklyReport.setProjectId(rset.getInt("projectId"));
				weeklyReport.setStaffId(rset.getInt("staffId"));
				weeklyReport.setWorkDateStart(Utilities.getCalendar(rset.getDate("workDateStart")));
				weeklyReport.setWorkDateEnd(Utilities.getCalendar(rset.getDate("workDateEnd")));
				weeklyReport.setTotalHoursWorked(rset.getDouble("totalHoursWorked"));
				weeklyReport.setProblem(Utilities.convUniqueCharacter(rset.getString("problem")));
				weeklyReport.setComment(Utilities.convUniqueCharacter(rset.getString("comment")));
				weeklyReport.setUpDay(Utilities.getCalendar(rset.getDate("upDay")));
				answer.add(weeklyReport);
            }
        } finally {
            if(rset != null)
                rset.close();
            if(pstmt != null)
                pstmt.close();
        }
		return (WeeklyReport[])answer.toArray(new WeeklyReport[0]);
	}
}
